package com.zmn.mcc.admin.controller.common.upload;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.common.utils.Objects;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.dto2.AMISResponseDTO;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.admin.utils.ImageUploadUtil;
import com.zmn.mcc.business.interfaces.pic.PicUploadBService;
import com.zmn.mcc.common.dto.upload.FileResponseDRO;
import com.zmn.mcc.common.dto.upload.FileUploadResponseDTO;
import com.zmn.mcc.common.dto.upload.HttpResultDTO;
import com.zmn.mcc.model.dto.upload.FileUploadReslutDTO;
import com.zmn.tapi.common.aliyun.sts.AccessKeyInfo;
import com.zmn.tapi.dubbo.interfaces.aliyun.OssRemoteService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用文件上传
 *
 * @author linfeng
 * @version v1.0
 * @since 2020/02/17 14:18
 */
@Controller
@RequestMapping("/common/")
public class FileUploadController {

    private Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    /**
     * 通用文件路经
     */
    private static final String COMMON_FILE_PATH = "common/file/";

    @DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private OssRemoteService ossRemoteService;

    @NacosValue("${tapi.upload.image.url}")
    private String tapiUploadImageUrl;

    /**
     * 上传附件
     * @param file
     * @param folderName 自己功能的目录名称，方便区分使用
     * @param fileName 自己定义的文件名称，如果该参数未传，则使用文件自己的名称
     * @return
     */
    @RequestMapping(value = "uploadFile")
    @ResponseBody
    public FileUploadReslutDTO uploaderFile(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "folderName", required = false) String folderName,
                                            @RequestParam(value = "fileName", required = false) String fileName) {
        String directory = COMMON_FILE_PATH;
        if (StringUtil.isNotBlank(folderName)) {
            directory += folderName;
        } else {
            directory += "default";
        }

        if (StringUtil.isBlank(fileName)) {
            fileName = file.getOriginalFilename();
        } else {
            String originFileName = file.getOriginalFilename();
            String[] array = originFileName.split("\\.");
            if (array != null && array.length > 1) {
                fileName = fileName + "." + array[1];
            }
        }
        try {
            return getResponseDTO(file,directory,fileName);
        } catch (Exception e) {
            logger.error("[zmn]上传附件异常，message:{}", e.getMessage());
            return new FileUploadReslutDTO(GlobalDict.RESULT_FAIL, "文件上传失败", null);
        }
    }


    private FileUploadReslutDTO getResponseDTO(@RequestParam("file") MultipartFile file, String directory, String fileName) {
        Map<String, String> otherParams = buildUploadPicParams(directory, fileName);
        String res = ImageUploadUtil.postMultipartImage(tapiUploadImageUrl, file, "file", Collections.emptyMap(), otherParams);
        if (StringUtil.isNotBlank(res)) {
            HttpResultDTO httpResultDTO = JSON.parseObject(res, HttpResultDTO.class);
            FileUploadResponseDTO fileUploadResponseDTO = JSON.parseObject(httpResultDTO.getData(), FileUploadResponseDTO.class);
            FileUploadReslutDTO fileUploadReslutDTO = new FileUploadReslutDTO();
            String url = fileUploadResponseDTO.getUrl();
            fileUploadReslutDTO.setCode(GlobalDict.RESULT_SUCCESS);
            fileUploadReslutDTO.setMsg(GlobalConsts.SUCCESS_MSG);
            FileUploadReslutDTO.Data data = new FileUploadReslutDTO.Data();
            data.setSrc(url);
            data.setName(fileName);
            data.setSize(file.getSize());
            fileUploadReslutDTO.setData(data);
            logger.info("[zmn]上传附件成功，URL: {}", url);
            return fileUploadReslutDTO;
        }
        return new FileUploadReslutDTO(GlobalDict.RESULT_FAIL, "文件上传失败", null);
    }


    private Map<String, String> buildUploadPicParams(String directory, String fileName) {
        ResponseDTO<AccessKeyInfo> accessKeyInfoResponseDTO = ossRemoteService.applyAccessKey("mcc", "");
        Map<String, String> others = new HashMap<>(16);
        logger.info("#applyAccessKey# {}", accessKeyInfoResponseDTO);
        if (accessKeyInfoResponseDTO.isSuccess() && Objects.nonNull(accessKeyInfoResponseDTO.getData())) {
            AccessKeyInfo data = accessKeyInfoResponseDTO.getData();
            others.put("directory", directory);
            others.put("securityToken", data.getSecurityToken());
            others.put("fileName", fileName);
            others.put("accessKeySecret", data.getAccessKeySecret());
            others.put("accessKeyId", data.getAccessKeyId());
        }
        return others;
    }
}
